package com.sun.item.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.sun.commons.utils.JsonUtils;
import com.sun.dubbo.webmanage.service.TbItemCatDubboService;
import com.sun.item.pojo.PortalItemCatMenu;
import com.sun.redis.dao.RedisDao;
import com.sun.webmanage.model.TbItemCat;

@Service("ItemMenuService")
public class ItemMenuServiceImpl implements ItemMenuService{

	@Reference
	private TbItemCatDubboService TbItemCatDubboService;
	@Resource
	private RedisDao RedisDao;
	@Value("${portal.cache.catmenu}")
	private String jedis_menu_key;

	@Override
	public Map<String, Object> listAllCatMenu() {
		Map<String,Object> retMap = new HashMap<>(4);
		
		if(RedisDao.exists(jedis_menu_key)){
			String jsonkey = RedisDao.getKey(jedis_menu_key);
			List<Object> jsonToList = JsonUtils.jsonToList(jsonkey, Object.class);
			retMap.put("data", jsonToList);
		}else{
			List<TbItemCat> parentCat = TbItemCatDubboService.listTbItemCatByPid(0);
			List<Object> listLoadCat = listLoadCat(parentCat);
			RedisDao.setKey(jedis_menu_key,JsonUtils.objectToJson(listLoadCat));
			retMap.put("data", listLoadCat);
		}
		
		return retMap;
	}
	
	private List<Object> listLoadCat(List<TbItemCat> parentCat){
		List<Object> listdata = new ArrayList<>();
		PortalItemCatMenu menu = null;
		for(TbItemCat cat:parentCat){
			if(cat.getIsParent()){
		    menu = new PortalItemCatMenu();
			menu.setU("/products/"+cat.getId()+".html");
			menu.setN(cat.getName());
			menu.setI(listLoadCat(TbItemCatDubboService.listTbItemCatByPid(cat.getId())));
			listdata.add(menu);
			}else{
			listdata.add("/products/"+cat.getId()+".html|"+cat.getName()+"");	
			}
		}
		
		return listdata;
	}
}
